<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>制卡</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-columns: 2fr 8fr;
            width: 100%;
        }

        /*中部右部分布局*/
        .central-right-layout {
            display: grid;
            grid-template-rows: 70px 470px 50px;
            width: 90%;
            margin: 0 auto;
        }

        /*中部左部分布局*/
        .central-left-layout {
            border: 1px solid black;
            display: grid;
            height: 590px;
            grid-template-rows: auto 1fr;
        }

        /*
        中部头部布局
        */
        .central-head {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: flex-start;
            gap: 200px;
            padding: 5px;
        }

        /*左边菜单布局*/
        .unit-menu-element {
            background-color: #c6c7c8;
            border: 1px solid black;
            width: 80%;
            margin: 10px auto;
            display: grid;
            grid-template-columns: 1fr 60px;
            justify-items: center;
            align-items: center;
        }

        /*
        鼠标变成可点击
         */
        .unit-menu-element:hover {
            cursor: pointer;
        }

        .unit-menu-title {
            border-bottom: 1px solid black;
            font-size: large;
            font-weight: bold;
            text-align: center;
        }

        .unit-menu-body {
            overflow-y: auto;
        }

        #card-table td {
            max-width: 16vw;
        }
    </style>
</head>

<body>
    <div class="body-grid">
        <!--头部-->
        <div class="header-grid">
            <!--    返回按钮-->
            <div>
                <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='number.html';">
                    &#xe623;
                </button>
            </div>
            <div class="page-title" id="page-title">
                <script>
                    document.getElementById("page-title").innerText = window.sessionStorage.getItem("competitionName")
                        + "--制卡"
                </script>
            </div>
            <!--    标题-->
            <div></div>
        </div>
        <!--中部-->
        <div class="central-layout">
            <div class="central-left-layout">
                <div class="unit-menu-title">参赛单位
                </div>
                <div class="unit-menu-body">
                    <!--                <div class="unit-menu-element">-->
                    <!--                    <div>参赛单位1fsdadsafdafasfdfdsaf</div>-->
                    <!--                    <div>已完成</div>-->
                    <!--                </div>-->
                </div>
            </div>
            <div class="central-right-layout">
                <div class="central-head">
                    <!--                搜索框组件-->
                    <div style="width: 450px;">
                        <div class="input-group">
                            <input id="search-input" type="text" class="form-control"
                                placeholder="可按选手姓名、单位名称、组别和指卡号搜索 . . .">
                            <button class="btn btn-outline-secondary iconfont" type="button"
                                onclick="showSearch()">&#xe60a;
                            </button>
                        </div>
                    </div>
                    <div>
                        <span id="unfinishedNumId" style="margin-right: 30px;">还有0人未发卡</span>
                        <button id="makeCardBtn" class="btn btn-primary" onclick="websocketConnect()">
                            开始录入
                        </button>
                        <span id="makeCardMsg2" style="margin-left:10px;color:red;display:none;">请连接读卡器设备</span>
                        <span id="makeCardMsg" style="margin-left:10px;color:red;display:none;">请放置指卡</span>
                    </div>

                </div>
                <div class="table-responsive">
                    <table id="card-table" class="table table-sm table-bordered text-center">
                        <thead>
                            <tr>
                                <th>指卡号</th>
                                <th>姓名</th>
                                <th>组别</th>
                                <th>性别</th>
                                <th>参赛单位</th>
                            </tr>
                        </thead>
                        <tbody id="card-tbody" class="table-group-divider">
                        </tbody>
                    </table>
                </div>
                <div>
                    <!--    分页组件-->
                    <ul class="pagination page-ul-flex" id="pagination">
                    </ul>
                </div>
            </div>
        </div>
        <!--尾部-->
        <div class="footer-grid">
            <!--网格留空-->
            <div></div>
            <!--进度条-->
            <div id="progress-bar" class="progress-bar-flex">
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">新增赛事</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">新增项目</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">设置组别</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">导入选手</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">下发号码</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">制卡</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">签到</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">批次管理</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">规则设置</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">开始比赛</div>
                    <i class="iconfont progress-bar-arrow">&#xe604;</i>
                </div>
                <div class="progress-bar-grid">
                    <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                    <div class="progress-bar-text">成绩计算</div>
                    <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
                </div>
            </div>
            <!--   下一步-->
            <div>
                <button class="btn btn-primary iconfont next-button"
                    onclick="nextProgress(SIGN_IN_PROGRESS,'sign-in.html')" id="btn-progress">&#xe65b;
                </button>
            </div>
        </div>
    </div>

    <script src="../js/pages.js"></script>
    <script src="../api/urls.js"></script>
    <script src="../js/dialog.js"></script>
    <script src="../js/progress.js"></script>
    <script src="../js/request.js"></script>
    <script>
        updateProgress("progress-bar", CARD_ISSUANCE_PROGRESS);

        //页码
        let pageNum = 1;
        //一页多少条
        let pageSize = 20;
        //总条数
        let total;
        //总页数
        let pages;
        //请求记录
        let records;
        //搜索内容
        let searchAll;
        //单位id
        let unitId;
        //未完成的人数
        let unfinishedNum = 0;
        //websocket对象
        let socket = {};
        //旧的目录
        let oldMenuBody;


        window.onload = async function () {
            //每次刷新页面必须关闭串口，以防之前打开的串口未被关闭
            await closePort()
        }

        /**
         * 点击搜索
         */
        async function showSearch() {
            pageNum = 1;
            await showPage();
        }

        /**
         * 渲染表格
         */
        function drawCardTable(records) {
            let unfinished = document.getElementById("unfinishedNumId");
            unfinished.textContent = "还有" + unfinishedNum + "个人未完成发卡";
            let tableBody = document.getElementById("card-tbody");
            tableBody.innerHTML = "";

            if (unfinishedNum <= 0 || new Date().getTime() > new Date(window.sessionStorage.getItem("competitionTime")).getTime()) {
                document.getElementById("makeCardBtn").disabled = "true";
            } else {
                document.getElementById("makeCardBtn").disabled = "";
            }


            if(new Date().getTime() < new Date(window.sessionStorage.getItem("competitionTime")).getTime()){//指卡号存在空的并且现在的时间早于比赛的开始时间，禁止下一步
                document.getElementById("btn-progress").disabled = true;
            }

            for (let record of records) {
                let trElement = document.createElement("tr");
                trElement.dataset.numberId = record.id;
                let tdElement1 = document.createElement("td");
                tdElement1.textContent = record.number;
                let tdElement2 = document.createElement("td");
                tdElement2.textContent = record.name;
                let tdElement3 = document.createElement("td");
                tdElement3.textContent = record.group;
                let tdElement4 = document.createElement("td");
                tdElement4.textContent = record.gender;
                let tdElement5 = document.createElement("td");
                tdElement5.textContent = record.unit;
                trElement.append(tdElement1, tdElement2, tdElement3, tdElement4, tdElement5);
                tableBody.append(trElement);
                console.log(record)
                if (!record.number){ 
                    document.getElementById("btn-progress").disabled = true;
                }
            }


        }

        //实现分页的方法
        async function getPage(pageNum, pageSize) {
            let searchInput = document.getElementById("search-input");
            searchAll = searchInput.value;
            let url = new URL(CARD_URL + "/searchAll");
            url.searchParams.set("pageNum", pageNum);
            url.searchParams.set("pageSize", pageSize);
            url.searchParams.set("unitId", unitId);
            url.searchParams.set("searchAll", searchAll);
            await fetch(url).then(response => {
                if (response.ok && response.headers.get("Content-Type") === "application/json") {
                    return response.json();
                } else {
                    throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
                }
            }).then(pageInfo => {
                pages = pageInfo.pages;
                total = pageInfo.total;
                records = pageInfo.records;

                drawCardTable(records);
            }).catch(error => {
                console.log("分页错误：", error);
            });

        }

        //上一页
        async function prePage() {
            pageNum = pageNum - 1;
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

        //下一页
        async function nextPage() {
            pageNum = pageNum + 1;
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages)
        }

        //点击切换
        async function handlePage(page) {
            if (page !== pageNum) {
                pageNum = page
                await getPage(pageNum, pageSize);
                createpage(pageNum, pageSize, total, pages);
            }

        }

        /**
         * 改变每页条数
         */
        async function changePageSize(value) {
            pageSize = Number(value);
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

        // 创建分页组件
        async function showPage() {
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);

            let url = new URL(PROJECT_URL + "/getEarliestProject");
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
            let res = await fetch_http({
                url: url,
                method: 'GET'
            })
            if (res.code == 200 && new Date().getTime() > new Date(res.data.startTime).getTime()) {  //如果当前时间超过第一个项目的开始时间 该按钮禁用
                let batchSign = document.getElementById("makeCardBtn")
                batchSign.disabled = true;
            }
        }

        /**
         * 渲染目录
         */

        function drawMenu(dataList) {
            let menuBody = document.querySelector(".unit-menu-body");
            oldBodyTable = menuBody
            menuBody.innerHTML = ''
            for (let data of dataList) {
                let divP = document.createElement("div");
                divP.classList.add("unit-menu-element");
                // divP.dataset.unitId=data.unitId;
                // divP.dataset.unfinishedNum=data.unfinishedNum;
                let divName = document.createElement("div");
                divName.textContent = data.unitName;
                let divStatus = document.createElement("div");
                if (data.unfinishedNum !== 0) {
                    divStatus.textContent = "未完成";
                } else {
                    divStatus.textContent = "已完成";
                }

                if (data.unfinishedNum <= 0) {
                    document.getElementById("makeCardBtn").disabled = true;
                } else {
                    document.getElementById("makeCardBtn").disabled = false;
                }

                divP.append(divName, divStatus);
                divP.addEventListener("click", async () => {
                    unitId = data.unitId;
                    unfinishedNum = data.unfinishedNum;
                    let searchInput = document.getElementById("search-input");
                    searchInput.value = null;
                    searchAll = searchInput.value;
                    await showPage();
                })
                menuBody.append(divP);
            }
        }

        /**
         *生成目录
         */
        async function getMenu() {
            let url = new URL(CARD_URL + "/getMenu");
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
            await fetch(url).then(resp => { return resp.json() }).then(result => {
                drawMenu(result);
            });
        }

        if (window.sessionStorage.getItem("competitionId")) {
            (async () => {
                await getMenu();
                let menuBody = document.querySelector(".unit-menu-body");
                if (oldMenuBody == null) {
                    menuBody.firstElementChild.click();
                }
                for (let k = 0; k < menuBody.children.length; k++) {
                    if (menuBody.children[k].lastElementChild.innerText == '未完成') {
                        menuBody.children[k].click();
                        break;
                    }
                }


            })();


        }

        function websocketConnect() {
            const ws_url = WEBSOCKET_BASE_URL + unitId;
            socket = new WebSocket(ws_url)

            socket.onopen = async function () {
                var makeCardBtn = document.getElementById('makeCardBtn')
                var makeCardMsg = document.getElementById('makeCardMsg')
                var makeCardMsg2 = document.getElementById('makeCardMsg2')

                let res = await openPort()

                if (res.code !== '200') {
                    //断开连接并关闭串口
                    await socket.close()
                    makeCardMsg2.style.display = ''


                } else {
                    makeCardBtn.onclick = closeWebsocket
                    makeCardBtn.innerText = "结束录入"
                    makeCardBtn.className = "btn btn-danger"
                    makeCardMsg.style.display = ''
                    makeCardMsg.innerText = '请放置指卡'
                    makeCardMsg2.style.display = 'none'
                    oldMenuBody = document.querySelector(".unit-menu-body").innerHTML
                }

            }

            socket.onmessage = async function (event) {
                var makeCardMsg = document.getElementById('makeCardMsg')
                makeCardMsg.innerText = event.data
                if (event.data === '读卡结束......') {
                    await getMenu();
                    let menuBody = document.querySelector(".unit-menu-body");
                    for (let k = 0; k < menuBody.children.length; k++) {
                        if (menuBody.children[k].lastElementChild.innerText == '未完成') {
                            menuBody.children[k].click();
                            break;
                        }
                    }
                }
                let menuBody = document.querySelector(".unit-menu-body");
                if (oldMenuBody !== menuBody.innerHTML) {
                    socket.close()
                    location.reload(true)
                }
            }

            socket.onclose = async function () {
                await closePort()
                socket = null

                var makeCardBtn = document.getElementById('makeCardBtn')
                var makeCardMsg = document.getElementById('makeCardMsg')
                makeCardBtn.onclick = websocketConnect
                makeCardBtn.innerText = "开始录入"
                makeCardBtn.className = "btn btn-primary"
                makeCardMsg.style.display = 'none'

            }

            socket.onerror = function () {
                socket.close()
            }

        }

        //串口通信打开请求
        async function openPort() {
            let url = new URL(BASE_URL + '/cardWebsocket/openPort')
            url.searchParams.set("unitId", unitId)
            url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"))
            url.searchParams.set("pageNum", pageNum);
            url.searchParams.set("pageSize", pageSize);
            let res = await fetch_http({
                url: url,
                method: 'get'
            })
            return res
        }

        //串口通信关闭请求
        async function closePort() {
            let url = new URL(BASE_URL + '/cardWebsocket/closePort')
            let res = await fetch_http({
                url: url,
                method: 'get',
            })
            return res
        }

        //关闭websocket
        async function closeWebsocket() {
            //断开连接并关闭串口,改变按钮状态
            socket.close()
        }

        //按照参赛单位录入指卡
        function makeCard() {
            //根据单位id获取所有的未制卡成员
            let url = new URL(CARD_URL + "/searchAll");
            url.searchParams.set("pageNum", pageNum);
            url.searchParams.set("pageSize", pageSize);
            url.searchParams.set("unitId", unitId);
            url.searchParams.set("searchAll", searchAll);


        }
    </script>
</body>

</html>